import { useEffect, useState, useMemo, Fragment } from "react";
import * as api from "@/api/product";
import { Table, Image, Button, Spin, message, Modal, Form, Input } from "antd";
import { DeleteOutlined, EditOutlined, EyeOutlined } from "@ant-design/icons";
import Dialog from "@/components/Dialog";
import { getCategory } from "../../../api/product";

import Uploader from "../../../components/Dialog/Upload";
const ProductCategory = () => {
  let [category, setCategory] = useState([]);
  let [visible, setVisible] = useState(false);
  let [show, setShow] = useState(false);
  let [compile, setCompile] = useState(false);
  let [loading, setLoading] = useState(false);
  let [currentRow, setCurrentRow] = useState({});
  let getCategoryList = () => {
    setLoading(true);
    api.getCategory().then((res) => {
      console.log(res);
      setCategory([...res.data.data].reverse());
      setLoading(false);
    });
  };
  let handleDeleteCategory = () => {
    let { cId: category_id } = currentRow;
    api.deleteCategory(category_id).then((res) => {
      if (res.data.state) {
        getCategoryList();
        message.success("删除成功");
      } else {
        message.error("删除失败," + res.data.msg);
      }
    });
  };
  useEffect(() => {
    getCategoryList();
  }, []);

  let dataSource = useMemo(() => {
    console.log(category);
    return category.map((item) => ({
      cImg: item.categoryImgurl,
      cId: item.category_id,
      cName: item.categoryName,
      cCTime: item.createTime,
      creator: item.creator,
      updateTime: item.updateTime,
      updator: item.updator,
      key: item._id,
    }));
  }, [category]);

  console.log(dataSource);

  let titles = [
    "类目图片",
    "类目id",
    "类目名称",
    "创建时间",
    "创建人",
    "更新时间",
    "更新人",
  ];

  let columns = useMemo(() => {
    let col = [];
    try {
      let keys = Object.keys(dataSource[0]);
      col = titles.map((title, index) => {
        if (keys[index] === "cImg") {
          return {
            title,
            key: keys[index],
            dataIndex: keys[index],
            width: 100,
            align: "center",
            render(v, r) {
              return (
                <Image
                  width={50}
                  src={
                    v
                      ? v
                      : "https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
                  }
                ></Image>
              );
            },
          };
        } else {
          return {
            align: "center",
            title,
            key: keys[index],
            dataIndex: keys[index],
          };
        }
      });

      let lastColumnObj = {
        title: "操作",
        key: "operate",
        align: "center",
        render(_, r) {
          return (
            <Fragment>
              <Button icon={<EyeOutlined />}>查看</Button>
              <Button
                icon={<EditOutlined />}
                onClick={() => {
                  setCompile(true);
                  setCurrentRow(r);
                  console.log(r);
                }}
              >
                编辑
              </Button>
              <Button
                onClick={() => {
                  setShow(true);
                  setCurrentRow(r);
                }}
                danger
                icon={<DeleteOutlined />}
              >
                删除
              </Button>
            </Fragment>
          );
        },
      };
      //添加到数组末尾
      col.push(lastColumnObj);
      return col;
    } catch (e) {
      console.log(e);
    }
  }, [category]);

  let handleOk = (instance) => {
    console.log(instance);
    //调用表单提交的方法
    instance.current.submit();
    setVisible(false);
  };

  let handleSetCategoryImgurl = (imgUrl) => {
    console.log(imgUrl);
  };

  let handleCancel = () => {
    setVisible(false);
  };
  //添加
  let handleAdd = () => {
    setVisible(true);
  };
  const onFinish = (values) => {
    console.log("Success:", values);
  };

  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };
  return (
    <Fragment>
      <Modal
        title="删除提示"
        content
        visible={show}
        onOk={() => {
          //删除数据
          handleDeleteCategory();
          //关闭弹框
          setShow(false);
        }}
        onCancel={() => {
          setShow(false);
          message.info("已取消删除");
        }}
        okText="确认"
        cancelText="取消"
      >
        <b>将永久删除数据,是否确定?</b>
        <br />
        <br />
        <br />
        <b style={{ color: "red" }}>警告————删除后无法恢复</b>
        <br />
        <br />
        <br />
      </Modal>
      <Modal
        title="编辑"
        content
        visible={compile}
        onOk={() => {
          handleDeleteCategory();
          //关闭弹框
          setCompile(false);
        }}
        onCancel={() => {
          setCompile(false);
          message.info("已取消编辑");
        }}
        okText="确认"
        cancelText="取消"
      >
        <Form
          name="basic"
          labelCol={{
            span: 8,
          }}
          wrapperCol={{
            span: 16,
          }}
          initialValues={{
            remember: true,
          }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item label="类目图片" name="cagtegorPic">
            <Uploader onUpload={handleSetCategoryImgurl} />
          </Form.Item>
          <Form.Item
            label="类目名称"
            name="类目名称"
            rules={[
              {
                required: true,
                message: "Please input your username!",
              },
            ]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
      <Dialog
        onOk={handleOk}
        visible={visible}
        onCancel={handleCancel}
        handleGetCategory={getCategoryList}
      />
      <Button type="primary" onClick={handleAdd}>
        点击增加
      </Button>
      <Table
        bordered
        dataSource={dataSource}
        columns={columns}
        loading={loading}
      ></Table>
    </Fragment>
  );
};

export default ProductCategory;
